<script
	lang="ts"
	setup
>
import { publishUploadFilePost, roleListAllGet, sysuserPost, sysuserPut } from '@/api'
import EmptyModal from '@/components/EmptyModal.vue'
import type { ISysuserPost, ISysuserPut } from '@/typed/request'
import { type FormInst, type FormRules } from 'naive-ui'
import { computed, onMounted, ref, watch } from 'vue'

interface IProps {
	show: boolean;
	data?: any;
	width?: number | string;
}

const formRef = ref<FormInst | null>(null)
const emit = defineEmits(['update:show', 'update:list'])
const props = withDefaults(defineProps<IProps>(), {
	width: 500
})
const initForm: ISysuserPost = {
	phone: '',
	password: '',
	userName: '',
	avatar: '',
	email: '',
	status: 0,
	roleIdList: [],
	remark: '',
};

const loading = ref(false)
const modalForm = ref<ISysuserPost>({ ...initForm })
const modalTitle = computed(() => {
	if (props.data?.userId) {
		return '编辑管理员'
	}
	return '添加管理员'
})

const rules: FormRules = {
	userName: [{
		required: true,
		message: '请输入用户名称',
		trigger: ['blur', 'input']
	}],
	password: [{
		required: true,
		message: '请输入密码',
		trigger: ['blur', 'input']
	}],
	phone: [{
		pattern: /^1[3-9]\d{9}$/,
		message: '请输入正确的手机号',
		trigger: ['blur', 'input']
	}],
	email: [{
		type: 'email',
		required: true,
		message: '请输入正确的邮箱地址',
		trigger: ['blur', 'input']
	}]
}

watch(() => props.data, () => {
	if (props.data) {
		modalForm.value = {
			...props.data,
			roleIdList: props.data?.roles?.map(i => i.roleId) || [],
			password: undefined
		}
	} else {
		modalForm.value = { ...initForm };
	}

})

const isEdit = computed(() => !!props.data?.userId)

async function onAdd() {
	formRef.value?.validate(async (errors) => {
		if (!errors) {
			loading.value = true
			const { code } = props.data?.userId ? await sysuserPut(modalForm.value as ISysuserPut) : await sysuserPost(modalForm.value as ISysuserPost);
			loading.value = false
			if (code === 200) {
				window.$message.success('保存成功')
				modalForm.value = { ...initForm }

				emit('update:list')
				emit('update:show', false)
			}
		}
	})
}

function onCancel() {
	if (!loading.value) {
		emit('update:show', false)
		modalForm.value = { ...initForm }
	}
}
const roleOptions = ref<any[]>([])

// 获取角色列表
const getRoleList = async () => {
	const { code, data } = await roleListAllGet()
	if (code === 200) {
		roleOptions.value = data.map(item => ({
			label: item.roleName,
			value: item.roleId
		}))
	}
}

// 在组件挂载时获取角色列表
onMounted(() => {
	getRoleList()
})

const uploading = ref(false)

// 处理头像上传
const handleAvatarUpload = async (options: any) => {
	const { file, onFinish } = options
	uploading.value = true
	try {
		const formData = new FormData()
		formData.append('files', file.file)
		const { code, data } = await publishUploadFilePost(formData)
		if (code === 200 && data?.[0]) {
			modalForm.value.avatar = data
			window.$message.success('上传成功')
		}
	} catch (error) {
		window.$message.error('上传失败')
	} finally {
		uploading.value = false
		onFinish()
	}
}
</script>

<template>
	<EmptyModal
		:show="show"
		:width="600"
		:title="modalTitle"
		@confirm="onAdd"
		:on-negative-click="onCancel"
		:on-close="onCancel"
		:on-positive-click="onAdd"
		:positive-button-props="{ loading }"
	>
		<n-form
			ref="formRef"
			:model="modalForm"
			label-placement="left"
			label-width="140"
			:rules="rules"
		>
			<n-form-item
				label="用户名称"
				path="userName"
			>
				<n-input
					placeholder="请输入用户名称"
					v-model:value="modalForm.userName"
				/>
			</n-form-item>
			<n-form-item
				label="手机号"
				path="phone"
			>
				<n-input
					placeholder="请输入手机号"
					v-model:value="modalForm.phone"
				/>
			</n-form-item>
			<n-form-item
				label="邮箱"
				path="email"
			>
				<n-input
					placeholder="请输入邮箱"
					v-model:value="modalForm.email"
				/>
			</n-form-item>
			<n-form-item
				v-if="!isEdit"
				label="密码"
				path="password"
			>
				<n-input
					type="password"
					placeholder="请输入密码"
					v-model:value="modalForm.password"
				/>
			</n-form-item>
			<n-form-item
				label="头像"
				path="avatar"
			>
				<n-upload
					accept="image/*"
					:max="1"
					:custom-request="handleAvatarUpload"
					:show-file-list="false"
				>
					<n-space vertical>
						<n-avatar
							v-if="modalForm.avatar"
							:size="64"
							:src="modalForm.avatar"
						/>
						<n-button>
							<template #icon>
								<n-icon>
									<svg
										xmlns="http://www.w3.org/2000/svg"
										xmlns:xlink="http://www.w3.org/1999/xlink"
										viewBox="0 0 24 24"
									>
										<path
											d="M19 7v2.99s-1.99.01-2 0V7h-3s.01-1.99 0-2h3V2h2v3h3v2h-3zm-3 4V8h-3V5H5c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-8h-3zM5 19l3-4l2 3l3-4l4 5H5z"
											fill="currentColor"
										></path>
									</svg>
								</n-icon>
							</template>
							{{ modalForm.avatar ? '更换头像' : '上传头像' }}
						</n-button>
					</n-space>
				</n-upload>
			</n-form-item>
			<n-form-item
				label="角色"
				path="roleIdList"
			>
				<n-select
					multiple
					placeholder="请选择角色"
					v-model:value="modalForm.roleIdList"
					:options="roleOptions"
				/>
			</n-form-item>
			<n-form-item
				label="账号状态"
				path="status"
			>
				<n-switch
					v-model:value="modalForm.status"
					:checked-value="0"
					:unchecked-value="1"
				>
					<template #checked>启用</template>
					<template #unchecked>停用</template>
				</n-switch>
			</n-form-item>
			<n-form-item
				label="备注"
				path="remark"
			>
				<n-input
					type="textarea"
					placeholder="请输入备注信息"
					v-model:value="modalForm.remark"
				/>
			</n-form-item>
		</n-form>
	</EmptyModal>
</template>

<style
	lang="less"
	scoped
>
.n-upload {
	width: fit-content;
}
</style>
